import cv2
import numpy as np
import matplotlib.pyplot as plt
import os
# 创建保存字体图片的目录
os.makedirs('chars', exist_ok=True)
#读取灰度图并裁剪
image = cv2.imread("hanzi1.jpg",0)
cropped_image = image[400:3750, :]
#生成灰度图
fig, axes = plt.subplots(1, 7, figsize=(38, 5))
axes[0].imshow(cropped_image, cmap='gray')
axes[0].set_title("Grayscale Image")
#进行二值处理，
_, binary_image = cv2.threshold(cropped_image, 127, 255, cv2.THRESH_BINARY )
inverted_binary_image = cv2.bitwise_not(binary_image) # 取反操作，将黑色变为白色，白色变为黑色
#生成二值处理后的图像
axes[1].imshow(inverted_binary_image, cmap='gray')
axes[1].set_title("Grayscale Image")
#进行腐蚀操作，5*5的矩形，腐蚀两次
kernel = np.ones((5,5), np.uint8)
eroded_image = cv2.erode(inverted_binary_image, kernel, iterations=2)
#生成腐蚀后的图像
axes[2].imshow(eroded_image, cmap='gray')
axes[2].set_title("Grayscale Image")
#进行膨胀操作，膨胀次数为一次
dilated_image = cv2.dilate(eroded_image, kernel, iterations=1)
#生成膨胀后的图像
axes[3].imshow(dilated_image, cmap='gray')
axes[3].set_title("Grayscale Image")
#进行闭运算，运算次数为15次
closed_image = cv2.morphologyEx(dilated_image, cv2.MORPH_CLOSE, kernel,iterations=15)
#生成闭运算后的图像
axes[4].imshow(closed_image, cmap='gray')
axes[4].set_title("Grayscale Image")
#进行Canny的边缘检测，阈值在50-200
edges_image = cv2.Canny(closed_image, 50, 200)
#生成Canny边缘检测后的图像
axes[5].imshow(edges_image, cmap='gray')
axes[5].set_title("Grayscale Image")
#进行轮廓识别
contours, _ = cv2.findContours(edges_image.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 在原始图像上绘制标注框，并保存字体图片
for i, contour in enumerate(contours):
    x, y, w, h = cv2.boundingRect(contour)
    char_image = cropped_image[y:y + h, x:x + w]
    cv2.imwrite(f'chars/{i:3d}.png', char_image)  #利用imwrite将字体图片保存

    cv2.rectangle(cropped_image, (x, y), (x + w, y + h), (0, 255, 0), 2)
axes[6].imshow(cropped_image, cmap='gray')
axes[6].set_title("Grayscale Image")
output_path = 'grayscale_image.jpg'
cv2.imwrite(output_path, cropped_image)